/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exatrez.manager;

import com.google.inject.Inject;
import com.wideplay.warp.persist.Transactional;
import exatrez.dao.UserGroupDAO;
import exatrez.model.UserGroup;
import exatrez.stripes.ObservationConfiguration;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Mansur
 */
public class UserObsManager {
    
    private static Logger LOG = LoggerFactory.getLogger(UserObsManager.class);
    
    @Inject
    private UserGroupDAO userGroupDAO;
    @Inject
    private ObservationConfiguration obsConf;
    
    @Inject
    protected com.google.inject.Provider<Session> sessionProvider;
    
    private static String SUCCESS = "success";
    private static String FAIL = "fail";
    
    
    public List<UserGroup> listSelectedGroup(){
        StringBuilder sb = new StringBuilder("select p from UserGroup p ")
                .append("where p.group.groupId in (:crewId, :procId, :hsseId, :ismId) ")
                .append("and p.active = 'Y' ")
                .append("order by p.group.groupId ");
        
        Session session = sessionProvider.get();
        
        Query query = session.createQuery(sb.toString());
        query.setParameter("crewId", Integer.parseInt(obsConf.getProperty("group.crew")));
        query.setParameter("procId", Integer.parseInt(obsConf.getProperty("group.procurement")));
        query.setParameter("hsseId", Integer.parseInt(obsConf.getProperty("group.hsse")));
        query.setParameter("ismId", Integer.parseInt(obsConf.getProperty("group.ism")));
        
        return query.list();
    }
    
    @Transactional
    public String saveUserGroup(UserGroup ug){
        String result = FAIL;
        try{
            userGroupDAO.saveOrUpdate(ug);
            result = SUCCESS;
        }catch(Exception ex){
            ex.printStackTrace(); // for development only
            LOG.error("save Error : "+ex.getMessage());
        }
        
        return result;
    }
}
